package br.com.inventario.util;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 *
 * @author diogosantiago
 */
public class DateUtil {

    private Calendar cal;

    public DateUtil() {
        this(new Date());
    }

    public DateUtil(Date d) {
        cal = Calendar.getInstance();
        cal.setTime(d);
    }

    public void setTime(Date d) {
        cal.setTime(d);
    }

    public Date getTime() {
        return cal.getTime();
    }

    public String getTZ() {
        return cal.getTimeZone().getID();
    }

    public DateUtil toMidnight() {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        return this;
    }

    public DateUtil removeDays(int days) {

        Date d = cal.getTime();
        long time = d.getTime();
        time -= days * 24 * 3600 * 1000;
        d.setTime(time);
        cal.setTime(d);

        return this;
    }

    public DateUtil addMinutes(int minutes) {
        Date d = cal.getTime();
        long time = d.getTime();
        time += minutes * 60 * 1000;
        d.setTime(time);
        cal.setTime(d);

        return this;
    }

    public DateUtil toGMT() {
        return toTZ("GMT");
    }

    public DateUtil toTZ(String tz) {
        cal.setTimeZone(TimeZone.getTimeZone(tz));

        return this;
    }

    public int getDaysSince(Date date) {
        long millisecs = date.getTime();
        Date d = cal.getTime();
        long time = d.getTime();
        long daysMillisecs = time - millisecs;
        int days = (int) ((((daysMillisecs / 1000) / 60) / 60) / 24);
        return days;
    }

    public boolean isAfter(Date date) {
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date);
        return cal.after(cal2);
    }
}
